


import sqlite as sqlite

class ConnectDB:
	def __init__(self,*args, **kwds):
		self.Connect()
		self.CreateCursor()
		self.cursor.execute("SELECT * FROM sqlite_master;")
		if len(self.cursor.fetchall()) == 0:
			print "Base de dados inexistente. Criando base de dados..."
			self.cursor.execute("CREATE TABLE polymers (id INTEGER PRIMARY KEY, name VARCHAR(50));")
			self.cursor.execute("CREATE TABLE measurements (id INTEGER PRIMARY KEY, id_polymer INTEGER, timestamp VARCHAR(50), resistance REAL, temperature REAL);")
			self.Commit()
			print "Base de dados criada."
		self.CloseConnection()
	def Connect(self):
		self.connection = sqlite.connect('RSampler.db')
	def CloseConnection(self):
		if(self.connection != None):
			self.connection.close()
			self.connection = None
	def CreateCursor(self):
		if(self.connection != None):
			self.cursor = self.connection.cursor()
		else:
			raise "Erro ao abrir banco de dados"
	def Commit(self):
		if(self.connection != None):
			self.connection.commit()
		else:
			raise "Erro ao dar Commit"
	def InsertPolymer(self, pName):
		self.Connect()
		self.CreateCursor()
		self.cursor.execute("""
					select name, id
					from polymers
					where name='%s';"""
				%pName)
		res = self.cursor.fetchall()
		if len(res) != 0:
			return res[0][1]
		self.cursor.execute("""
					insert into polymers (name)
					values ('%s');"""
				%pName)
		self.cursor.execute("""
					select name, id
					from polymers
					where name='%s';"""
				%pName)
		result = self.cursor.fetchone()[1]
		self.Commit()
		self.CloseConnection()
		return result
	def InsertMeasurements(self, id_polymer, values):
		self.Connect()
		self.CreateCursor()
		for item in values:
			self.cursor.execute("""
						insert into measurements
						(id_polymer, timestamp, resistance, temperature)
						values ('%s', '%s', '%s', '%s');"""
					%(id_polymer, item['date'], item['resistance'], item['temperature']))
		self.Commit()
		print "Dados salvos"
		self.CloseConnection()
	def RetrievePolymers(self):
		self.Connect()
		self.CreateCursor()
		self.cursor.execute("""
					select name, id
					from polymers
				""")
		res = self.cursor.fetchall()
		print res
		self.Commit()
		self.CloseConnection()
		return res
	def __del__(self):
		self.CloseConnection()
		print "Conexao Fechada"
